package gnss

type RtcmEpochBufDecoder struct {
	onlymsm     int8
	epochn      int8
	lastsow     int
	rtcmDec     *Rtcm3RawBufDecoder
	OnEpochDone func(sow int, n int8, flag int8)
	OnMsmBuf    func(msgid uint16, sys byte, sow int, sync byte, rtcmBuf []byte)
	OnRtcmBuf   func(msgid uint16, rtcmBuf []byte) bool
}

func NewRtcmEpochBufDecoder() *RtcmEpochBufDecoder {
	rval := &RtcmEpochBufDecoder{}
	rval.init()
	return rval
}

func (this *RtcmEpochBufDecoder) onMsmBuf(msgid uint16, sys byte, sow int, sync byte, buf []byte) {
	evt := this.OnMsmBuf
	if evt != nil {
		evt(msgid, sys, sow, sync, buf)
	}
}

func (this *RtcmEpochBufDecoder) InputBuf(buf []byte) {
	this.rtcmDec.InputBuf(buf)
}

/*
flag
0:正常结束
1: 非正常结束
*/
func (this *RtcmEpochBufDecoder) doEpochDone(sow int, n int8, flag int8) {
	evt := this.OnEpochDone
	if evt != nil {
		evt(sow, n, flag)
	}
	this.epochn = 0
}

func (this *RtcmEpochBufDecoder) init() {
	this.rtcmDec = NewRtcm32RawBufDecoder("")
	this.rtcmDec.OnRtcmBuf = func(rtcmBuf []byte) {
		msgid := GetRtcmMsgId(rtcmBuf, 24)
		evt := this.OnRtcmBuf
		if evt != nil {
			if !evt(uint16(msgid), rtcmBuf) {
				return
			}
		}
		if RtcmIsObsMsm(msgid) {
			_, _, sys, sow, sync := ExtractInfoFromRtcmBuf(rtcmBuf, 24)
			if sync == 0 {
				this.epochn++
				this.onMsmBuf(uint16(msgid), sys, sow, sync, rtcmBuf)
				this.doEpochDone(sow, this.epochn, 0)
			} else if this.epochn > 0 && this.lastsow != sow { // 非正常结束
				this.doEpochDone(this.lastsow, this.epochn, 1)
				this.epochn++
				this.onMsmBuf(uint16(msgid), sys, sow, sync, rtcmBuf)
			} else {
				this.epochn++
				this.onMsmBuf(uint16(msgid), sys, sow, sync, rtcmBuf)
			}
			this.lastsow = sow
		}
	}
}
